package com.riteny.oauth.core.userauth;

import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public class CustomUserDetailsService implements UserDetailsService {

    private CustomUserAuthenticationService customUserAuthenticationService;

    public CustomUserDetailsService(CustomUserAuthenticationService customUserAuthenticationService) {
        this.customUserAuthenticationService = customUserAuthenticationService;
    }

    @Override
    public UserDetails loadUserByUsername(String username) {
        return new User(username, null, null);
    }

    public UserDetails loadUserByUsername(String username, String userType) {

        //獲取該用戶的密碼
        String password = customUserAuthenticationService.searchPassword(username, userType);

        //獲取該用戶的權限資料
        List<String> authorityStrList = customUserAuthenticationService.searchAuthorities(username, userType);

        List<SimpleGrantedAuthority> authorities =new ArrayList<>();
        Optional.ofNullable(authorityStrList).orElse(new ArrayList<>()).forEach(authorityStr->{
            authorities.add(new SimpleGrantedAuthority(authorityStr));
        });

        return new CustomUser(username, password, userType, authorities);
    }
}